package com.udata.server.servlet;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.udata.server.persistence.dao.CurrencyRateDao;

public class CurrencyRateServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6133599877684458113L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String action = req.getParameter("action");
		if (action == null) {
			try {
				CurrencyRateDao.getInstance().parseCurrencySource();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (action.equals("getCurrency")) {
			String from = req.getParameter("from");
			String startDate = req.getParameter("startDate");
			String endDate = req.getParameter("endDate");
			String to = req.getParameter("to");

			try {
				String json = CurrencyRateDao.getInstance().getJson(from,
						Arrays.asList(to.split(",")), startDate, endDate);
				this.sendResponseMsg(resp, json);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	protected void sendResponseMsg(HttpServletResponse response, String content)
			throws IOException {

		try {
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setContentType("text/plain");
			response.setCharacterEncoding("UTF-8");
			ServletOutputStream responseOutputStream = response
					.getOutputStream();

			responseOutputStream.write(content.getBytes("UTF-8"));
			responseOutputStream.flush();
			responseOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void dePost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		this.doGet(req, resp);
	}
}
